<?php
/*
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com

Copyright (c) 2005 osCommerce

Released under the GNU General Public License

@Author: Raphael Vullriede (osc@rvdesign.de)

Port to xtCommerce

@Author: Winfried Kaiser (w.kaiser@fortune.de)
*/

// ALTER TABLE admin_access ADD COLUMN google_sitemap INT(1) NOT NULL DEFAULT '0' ; 

require('includes/application_top.php');
if($_GET['action'] == 'generate') {
	// XML-Specification: https://www.google.com/webmasters/sitemaps/docs/de/protocol.html
	
	define('CHANGEFREQ_CATEGORIES', 'weekly');  // Valid VALUES are "always", "hourly", "daily", "weekly", "monthly", "yearly" and "never".
	define('CHANGEFREQ_PRODUCTS', 'daily'); // Valid VALUES are "always", "hourly", "daily", "weekly", "monthly", "yearly" and "never".
	
	define('PRIORITY_CATEGORIES', '1.0');
	define('PRIORITY_PRODUCTS', '0.5');
	
	define('MAX_ENTRYS', 50000);
	define('MAX_SIZE', 10000000);
	define('GOOGLE_URL', 'http://www.google.com/webmasters/sitemaps/ping?sitemap=');
	define('YAHOO_URL','http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=');
	define('ASK_URL','http://submissions.ask.com/ping?sitemap=');
	define('BING_URL','http://webmaster.live.com/ping.aspx?siteMap=');
	
	define('SITEMAPINDEX_HEADER', "<?xml version='1.0' encoding='UTF-8'?>".'
		<sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/siteindex.xsd">'."\n");
	define('SITEMAPINDEX_FOOTER', '</sitemapindex>');
	define('SITEMAPINDEX_ENTRY', "\t".'<sitemap>'."\n\t\t".'<loc>%s</loc>'."\n\t\t".'<lastmod>%s</lastmod>'."\n\t".'</sitemap>'."\n");
	
	define('SITEMAP_HEADER', "<?xml version='1.0' encoding='UTF-8'?>".'
		<urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">'."\n");
	
	define('SITEMAP_FOOTER', '</urlset>');
	define('SITEMAP_ENTRY', "\t".'<url>'."\n\t\t".'<loc>%s</loc>'."\n\t\t".'<priority>%s</priority>'."\n\t\t".'<lastmod>%s</lastmod>'."\n\t\t".'<changefreq>%s</changefreq>'."\n\t".'</url>'."\n");
	
	define('SITEMAP_CATALOG', HTTP_SERVER.DIR_WS_CATALOG);
	
	$usegzip        = false;
	$autogenerate   = false;
	$output_to_file = false;
	$notify_google  = false;
	$notify_url     = SITEMAP_CATALOG.'sitemap.xml';
	
	function output($string) {
		global $function_open, $function_close, $function_write, $fp, $autogenerate;
	
		if ($autogenerate) {
			$function_write($fp, $string);
		} else {
			echo $string;
		}
	}
	
	function output_entry() {
		global $string, $strlen, $c, $autogenerate, $fp, $function_open, $function_close, $main_content, $strlen;
		
		output($string);
		$strlen += strlen($string);
		$c++;
		if ($autogenerate) {
			// 500000 entrys or filesize > 10,485,760 - some space for the last entry
			if ( $c == MAX_ENTRYS || $strlen >= MAX_SIZE) {
				output(SITEMAP_FOOTER);
				$function_close($fp);
				$c = 0;
				$i++;
				$filename = 'sitemap'.$file_extension;
				$fp = $function_open($filename, 'w');
				$main_content = $main_content . "<br>Sitemap-Datei '<b>" . $filename . "</b>' erstellt.";
				output(SITEMAP_HEADER);
				$strlen = strlen(SITEMAP_HEADER);
			}
		}
	}
	function iso8601_date($timestamp) {
	
		if (PHP_VERSION < 5) {
			$tzd = date('O',$timestamp);
			$tzd = substr(chunk_split($tzd, 3, ':'),0,6);
			return date('Y-m-d\TH:i:s', $timestamp) . $tzd;
		} else {
			return date('c', $timestamp);
		}
	}
	
	// generates cPath with helper array
	function rv_get_path($cat_id, $code) {
		global $cat_array;
	
		$my_cat_array = array($cat_id);
	
		while($cat_array[$cat_id][$code]['parent_id'] != 0) {
			$my_cat_array[] = $cat_array[$cat_id][$code]['parent_id'];
			$cat_id = $cat_array[$cat_id][$code]['parent_id'];
		}
	
		return 'cPath='.implode('_', array_reverse($my_cat_array));
	}
	// request over http or command line?
	if (!isset($_SERVER['SERVER_PROTOCOL'])) {
	
		if (count($_SERVER['argv'] > 1)) {
	
			// option p ist only possible of min 1 more option isset
			if ( (strlen($_SERVER['argv'][1]) >= 2) && strpos($_SERVER['argv'][1], 'p') !== true) {
				$notify_google = true;
				$_SERVER['argv'][1] = str_replace('p', '', $_SERVER['argv'][1]);
			}
	
			switch($_SERVER['argv'][1]) {
	
				// dump to file
				case '-f':
				$output_to_file = true;
				$filename = $_SERVER['argv'][2];
				break;
	
				// dump to compressed file
				case '-zf':
				$usegzip        = true;
				$output_to_file = true;
				$filename = $_SERVER['argv'][2];
				break;
	
				// autogenerate sitemaps. useful for sites with more the 500000 Urls
				case '-a':
				$autogenerate = true;
				break;
	
				// autogenerate sitemaps and use gzip
				case '-za':
				$autogenerate   = true;
				$usegzip        = true;
				break;
			}
		}
	} else {
	
		if (count($_POST) > 0) {
	
			// dump to file
			if (isset($_POST['f'])) {
				$output_to_file = true;
				$filename = $_POST['f'];
			}
			// use gzip
			$usegzip = (isset($_POST['gzip']) && $_POST['gzip'] == true) ? true : false;
	
			// autogenerate sitemaps
			$autogenerate = (isset($_POST['auto']) && $_POST['auto'] == true) ? true : false;
	
			// notify google
			$notify_google = (isset($_POST['ping']) && $_POST['ping'] == true) ? true : false;
		}
	}
	
	// use gz... functions for compressed files
	if ($usegzip) {
		$function_open  = 'gzopen';
		$function_close = 'gzclose';
		$function_write = 'gzwrite';
	
		$file_extension = '.xml.gz';
	} else {
		$function_open  = 'fopen';
		$function_close = 'fclose';
		$function_write = 'fwrite';
	
		$file_extension = '.xml';
	}
	
	$c = 0;
	$i = 1;
	
	$sitemap_filename = '../sitemap'.$file_extension;
	// $sitemap_filename = '../sitemap'.$i.$file_extension;
	if ($autogenerate) {
		$filename = $sitemap_filename;
	}
	$autogenerate = $autogenerate || $output_to_file;
	if ($autogenerate) {
		$fp = $function_open($filename, 'w+');
		$main_content = "Sitemap-Datei '<b>" . $filename . "</b>' erstellt.";
	}
	$notify_url = SITEMAP_CATALOG.$sitemap_filename;
	
	output(SITEMAP_HEADER);
	$strlen = strlen(SITEMAP_HEADER);
	
	$cat_data = $db->db_query("
	    SELECT
	      c.categories_id,
	      c.parent_id,
	      cd.language_id,
	      UNIX_TIMESTAMP(c.date_added) as date_added,
	      UNIX_TIMESTAMP(c.last_modified) as last_modified,
	      l.code
	    FROM 
	      ".TABLE_CATEGORIES." c,
	      ".TABLE_CATEGORIES_DESCRIPTION." cd,
	      ".TABLE_LANGUAGES." l
	    WHERE
	      c.categories_id = cd.categories_id AND
	      cd.language_id = l.languages_id
	    ORDER by 
	      cd.categories_id
	  ");
	
	$cat_array = array();
	if ($cat_data->_numOfRows > 0) {
		while(!$cat_data->EOF) {
			$cat_array[$cat_data->fields['categories_id']][$cat_data->fields['code']] = $cat_data;
			$cat_data->MoveNext();
		}
	}
	reset($cat_array);
	
	foreach($cat_array as $lang_array) {
		foreach($lang_array as $cat_id => $cat_data) {
			$lang_param = ($cat_data->fields['code'] != DEFAULT_LANGUAGE) ? '&language='.$cat_data->fields['code'] : '';
			$date = ($cat_data->fields['last_modified'] != NULL) ? $cat_data->fields['last_modified'] : $cat_data->fields['date_added'];
			$string = sprintf(SITEMAP_ENTRY, htmlspecialchars(utf8_encode(href_link(FILENAME_DEFAULT, 
				rv_get_path($cat_data->fields['categories_id'], $cat_data->fields['code']).$lang_param))) ,PRIORITY_CATEGORIES, iso8601_date($date), CHANGEFREQ_CATEGORIES);
	
			$c_cat_total++;
			output_entry();
		}
	}
	
	$product_data = $db->db_query("
	    SELECT
	      p.products_id,
	      pd.language_id,
	      UNIX_TIMESTAMP(p.products_date_added) as products_date_added,
	      UNIX_TIMESTAMP(p.products_last_modified) as products_last_modified,
	      l.code
	    FROM
	      ".TABLE_PRODUCTS." p, 
	      ".TABLE_PRODUCTS_DESCRIPTION." pd,
	      ".TABLE_LANGUAGES." l 
	    WHERE
	      p.products_status='1' AND
	      p.products_id = pd.products_id AND
	      pd.language_id = l.languages_id
	    ORDER BY
	      p.products_id
	  ");
	
	if ($product_data->_numOfRows > 0) {
		while(!$product_data->EOF) {
			$lang_param = ($product_data->fields['code'] != DEFAULT_LANGUAGE) ? '&language='.$product_data->fields['code'] : '';
			$date = ($product_data->fields['products_last_modified'] != NULL) ? 
				$product_data->fields['products_last_modified'] : $product_data->fields['products_date_added'];
			$string = sprintf(SITEMAP_ENTRY, htmlspecialchars(utf8_encode(href_link(FILENAME_PRODUCT_INFO, 
				'products_id='.$product_data->fields['products_id'].$lang_param))) , 
				PRIORITY_PRODUCTS, iso8601_date($date), CHANGEFREQ_PRODUCTS);
	
			$c_prod_total++;
			output_entry();
			$product_data->MoveNext();
		}
	}
	
	output(SITEMAP_FOOTER);
	if ($autogenerate) {
		$function_close($fp);
	}
	
	$main_content .= "<br><br>" . $c_cat_total . " <b>Kategorien</b> und " . $c_prod_total . " <b>Produkte</b> exportiert.";
	// generates sitemap-index file
	if ($autogenerate && $i > 1) {
		$sitemap_index_file = 'sitemap_index'.$file_extension;
		$main_content = $main_content . "<br><br>Sitemap-Index-Datei '<b>" . $sitemap_index_file . "</b>' erstellt.";
		$notify_url = SITEMAP_CATALOG.$sitemap_index_file;
		$fp = $function_open('sitemap_index'.$file_extension, 'w');
		$function_write($fp, SITEMAPINDEX_HEADER);
		for($ii=1; $ii<=$i; $ii++) {
			$function_write($fp, sprintf(SITEMAPINDEX_ENTRY, SITEMAP_CATALOG.'sitemap'.$ii.$file_extension, iso8601_date(time())));
		}
		$function_write($fp, SITEMAPINDEX_FOOTER);
		$function_close($fp);
	}
	
	if (!function_exists('file_put_contents')) {
		function file_put_contents($filename, $content) {
			$fp = fopen($filename, 'w');
			fwrite($fp, $content);
			fclose($fp);
		}
	}
	
	function use_curl($i) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $ping_host[$i] . $ping_path[$i] . $request_uri);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);			
		$data = curl_exec($ch);
		curl_close($ch);

		return $data;
	}

	/*
		-> using fsockopen
	*/
	function use_fsockopen($i) {
		$sock = fsockopen(str_replace('http://', '', $ping_host[$i]), 80, $errno, $errstr, 5);
		fputs($sock, "GET " . $tping_path[$i] . $request_uri . " HTTP/1.1\r\n");
		fputs($sock, "Host: " . str_replace('http://', '',$ping_host[$i]) . "\r\n");
		fputs($sock, "Connection: close\r\n\r\n");
		while(!feof($sock)) {
			$data .= fgets($sock, 4096);
		}
		fclose($sock);
		return substr($data, strpos($data, '<'));
	}

	/*
		-> clean
	*/
	function clean($str) {
		$search = array (
						'#<head[^>]*?>.*?</head>#si',
						'#<body[^>]*?>#si',
						'#<html[^>]*?>#si',
						'#<html[^>]*?>#si',
						'#<meta[^>]*?>#si',
						);

		$replace = array(
						' ',
						' ',
						' ',
						' ',
						' '
						);

		$restr = preg_replace($search, $replace, $str);			
		return $restr;
	}
	
	$ping_service = array('Google', 'Yahoo!', 'Ask.com', 'Live Search');

	$ping_host = array('http://www.google.de', 'http://search.yahooapis.com', 'http://submissions.ask.com', 'http://webmaster.live.com');
										
	$ping_path = array('/webmasters/tools/ping?sitemap=', '/SiteExplorerService/V1/ping?sitemap=', '/ping?sitemap=', '/ping.aspx?siteMap=');
	
	$anzahl = sizeof($_POST['ping']);
	
	//function ping(){
		$ping = false;
		
		for($i=0; $i < $anzahl; $i++) {								
			if(!empty($anzahl[$i])) {					
				$ping = true;
				if (function_exists('curl_init')) {
					$main_content = '<div>' . clean(use_curl($i)). '</div>';
				} elseif(function_exists('fsockopen')) {
					$main_content = '<div>' . clean(use_fsockopen($i))	. '</div>';
				} else {
					$main_content =  TITLE_SITEMAP_FAILED;
				}
				$request		.= utf8_decode($main_content);
				$main_content		='';
				unset($main_content);				
			} 
		}			

		if($ping == true) {
			return 'Antwort ' . $ping_service . ' Teil 2<br />' . $request;
		} else {
			return;		
		}			
	//}

	/*
		-> using curl
	*/
	
	/*
	if ($_POST['google'] == 'ping') {
		if (function_exists('curl_init')) {
			$main_content = '<div style="display:none;" id="ping_' . $i . '">' . clean(use_curl($i))		. '</div>';
		} elseif(function_exists('fsockopen')) {
			$main_content = '<div style="display:none;" id="ping_' . $i . '">' . clean(use_fsockopen($i))	. '</div>';
		} else {
			$message = 'FEHLER!';
		}
		fopen(GOOGLE_URLL.urlencode($notify_url), 'r');
		$google_response = file_get_contents(GOOGLE_URL . urlencode($notify_url));
		$main_content .= "<br /><br />Google-Aufruf mit<br /><b>" . GOOGLE_URL . $notify_url . "</b><br /><br />" .
			'<b><font color="red">Google Antwort:</font></b><br />' .	$google_response;
	}
	if ($_POST['yahoo'] == 'ping') {
		fopen(YAHOO_URL.urlencode($notify_url), 'r');
		$yahoo_response = file_get_contents(YAHOO_URL . urlencode($notify_url));
		$main_content .= "<br /><br />Yahoo-Aufruf mit<br /><b>" . YAHOO_URL . $notify_url . "</b><br /><br />" .
			'<b><font color="red">Yahoo Antwort:</font></b><br />' .	$yahoo_response;
	}
	if ($_POST['ask'] == 'ping') {
		fopen(ASK_URL.urlencode($notify_url), 'r');
		$ask_response = file_get_contents(ASK_URL . urlencode($notify_url));
		$main_content .= "<br /><br />ASK-Aufruf mit<br /><b>" . ASK_URL . $notify_url . "</b><br /><br />" .
			'<b><font color="red">ASK Antwort:</font></b><br />' .	$ask_response;
	}
	if ($_POST['bing'] == 'ping') {
		fopen(BING_URL.urlencode($notify_url), 'r');
		$bing_response = file_get_contents(BING_URL . urlencode($notify_url));
		$main_content .= "<br /><br />Bing-Aufruf mit<br /><b>" . BING_URL . $notify_url . "</b><br /><br />" .
			'<b><font color="red">Bing Antwort:</font></b><br />' .	$bing_response;
	}
	*/
}

require(DIR_WS_INCLUDES . 'metatag.php');
?>
</head>
<body>

<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<div id="wrapper">
<table class="outerTable" cellpadding="0" cellspacing="0">
  <tr>
    <td class="columnLeft2" width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
		<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
    </table></td>
    <td class="boxCenter" width="100%" valign="top">
    	<table class="table_pageHeading" border="0" width="100%" cellspacing="0" cellpadding="0">
		  <tr>
		    <td class="pageHeading">Google Sitemap</td>
		  </tr>
		</table>
    	<?php
    		echo '<pre>';
    		print_r($_GET);
    		print_r($_POST);
    		echo '</pre>';
    		if($_GET['action'] == 'generate') {
    			echo $main_content; 
    		} else { 
    		?>
    			<form name="sitemap" action="google_sitemap.php?action=generate" method="POST">
    				<input type="hidden" name="auto" value="true">
    				<input type="checkbox" name="ping[]" value="google"> Google anpingen?<br />
    				<input type="checkbox" name="ping[]" value="yahoo"> Yahoo anpingen?<br />
    				<input type="checkbox" name="ping[]" value="ask"> ASK anpingen?<br />
    				<input type="checkbox" name="ping[]" value="bing"> Bing anpingen?<br />
    				<input class="button" type="submit" value="Start">
    			</form>
    	<?php } ?>
    </td>
  </tr>
</table>
</div>
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<br />
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>